package com.zzx.config;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zzx.domain.Conversation;
import com.zzx.service.impl.ConversationServiceImpl;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.MessageType;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
public class MySqlChatMemory implements ChatMemory {
    @Autowired
    private ConversationServiceImpl conversationService;

    @Override
    public void add(String conversationId, List<Message> messages) {
        messages.forEach(message -> {
            Conversation conversation = Conversation.builder()
                    .message(message.getText())
                    .type(message.getMessageType().getValue())
                    .createTime(LocalDateTime.now())
                    .conversationId(conversationId)
                    .build();
            conversationService.save(conversation);
        });
    }

    @Override
    public List<Message> get(String conversationId) {
        //根据id和type查询说的话
        //select * from conversation where conversationid = ?
        LambdaQueryWrapper<Conversation> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Conversation::getConversationId, conversationId);
        List<Conversation> list = conversationService.list(lqw);
        return list.stream().map(list1 -> {
            Message message = null;
            if (MessageType.ASSISTANT.getValue().equals(list1.getType())) {
                message = new AssistantMessage(list1.getMessage());
            } else if (MessageType.USER.getValue().equals(list1.getType())) {
                message = new UserMessage(list1.getMessage());
            }
            return message;
        }).toList();
    }

    @Override
    public void clear(String conversationId) {
        LambdaQueryWrapper<Conversation> lqw = new LambdaQueryWrapper<>();
        //delete from conversation where conversation = ?
        lqw.eq(Conversation::getConversationId,conversationId);
        conversationService.remove(lqw);
    }
}
